package com.syh.jn.scm.domain.operation.entity.system;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.spring.SpringContextUtils;
import cn.redscarf.commons.util.validator.ValidationUtils;
import cn.redscarf.commons.wrapper.Restrictions;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.domain.AbstractSimpleAggregate;
import com.syh.jn.scm.domain.operation.repository.system.DictReadRepository;
import com.syh.jn.scm.domain.operation.repository.system.DictTypeReadRepository;
import com.syh.jn.scm.domain.operation.repository.system.DictTypeRepository;
import com.syh.jn.scm.dto.operation.system.dict.DictTypeMto;
import com.syh.jn.scm.dto.operation.system.dict.DictTypeSto;
import com.syh.jn.scm.exception.BusinessException;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * Date:2018/7/12
 * Author:Clown
 * 运营平台字典类型;
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class DictType extends AbstractSimpleAggregate<Long> {
  private final static Long DEFAULT_SUP_ID = Long.valueOf("0");
  public static DictType createDictType(DictTypeSto sto){
    DictType dictType = DictType.commonCreatedDictType();
    ExtBeanUtils.copyProperties(sto,dictType);

    //判断父级分类
    if (sto.getSupId() == null) {
      dictType.cateLevel = 0;
      //TODO 需要生产code 的方案
      dictType.code = "0001";
      dictType.supId = DEFAULT_SUP_ID;
    } else {
      dictType.supId = sto.getSupId();
      DictTypeRepository dictTypeRepository = (DictTypeRepository) SpringContextUtils.getBean("dictTypeRepositoryImpl");
      DictType fatherCategory = dictTypeRepository.getById(dictType.getSupId());
      ExtAssert.notNull(fatherCategory, "父级分类不存在");
      if (!fatherCategory.getStatus().equals(Short.valueOf("1"))) {
        throw new BusinessException("父级分类处于停用状态");
      }
      dictType.cateLevel = fatherCategory.getCateLevel() + 1;
      dictType.code = fatherCategory.getCode() + "-" + "0001";
    }
    return dictType;
  }

  /**
   * 初始化一些参数
   * @return
   */
  private static DictType commonCreatedDictType(){
    DictType dictType = new DictType();
    dictType.status = 1;
    dictType.createTimeStamp = System.currentTimeMillis();
    return dictType;
  }

  /**
   * 编辑修改字典类型
   * @param mto
   */
  public void modify(DictTypeMto mto){
    ExtAssert.notNull(mto,"对象为空");
    ValidationUtils.validate(mto);
    ExtBeanUtils.copyProperties(mto, this);
    //判断父级分类
    if (mto.getSupId() == null) {
      this.cateLevel = 0;
      this.supId = DEFAULT_SUP_ID;
    } else {
      isFatherCate(mto.getId(), mto.getSupId());
      this.supId = mto.getSupId();
      DictTypeRepository dictTypeRepository = (DictTypeRepository) SpringContextUtils.getBean("dictTypeRepositoryImpl");
      DictType fatherCategory = dictTypeRepository.getById(this.getSupId());
      ExtAssert.notNull(fatherCategory, "父级分类不存在");
      if (!fatherCategory.getStatus().equals(Short.valueOf("1"))) {
        throw new BusinessException("父级分类处于停用状态");
      }
      this.cateLevel = fatherCategory.getCateLevel() + 1;
    }
    this.lastUpdateTimeStamp = System.currentTimeMillis();
  }

  /**
   * 递归判断不能是自己的父类或者父类的父类
   */
  private void isFatherCate(Long id, Long supId) {
    DictTypeReadRepository dictTypeQuery = (DictTypeReadRepository) SpringContextUtils.getBean(DictTypeReadRepository.class);
    DictType sup = dictTypeQuery.getById(supId);
    if (sup != null) {
      if (id.equals(sup.getId())) {
        throw new BusinessException("父类不能是自己或者自己的子类");
      }
      isFatherCate(id, sup.getSupId());
    }
  }

  /**
   * 数据销毁 todo 要先停用下面的字典
   */
  public void destroy() {
    DictTypeReadRepository dictTypeQuery = (DictTypeReadRepository) SpringContextUtils.getBean(DictTypeReadRepository.class);
    DictReadRepository dictQuery = (DictReadRepository) SpringContextUtils.getBean(DictReadRepository.class);
    Wrapper wrapper = Wrapper.build();
    wrapper.append(Restrictions.eq("categoryId", this.id));
    Integer upstreamCount = dictQuery.getCount(wrapper);
    if (upstreamCount > 0) {
      throw new BusinessException("该分类已经被供应商使用,不可以删除 !");
    }
    Wrapper cateWrapper = Wrapper.build();
    cateWrapper.append(Restrictions.eq("supId", this.id));
    Integer dsCate = dictTypeQuery.getCount(cateWrapper);
    if (dsCate > 0) {
      throw new BusinessException("该分类被其它分类引用了,不可以删除,要删除的话,就先删除引用分类!");
    }
  }

  /**
   * 启用分类
   */
  public void enabled() {
    this.status = 1;
  }

  /**
   * 停用分类
   */
  public void disabled() {
    this.status = -1;
  }
  /**
   * 上级分类id
   */
  private Long supId;
  /**
   * 分类编码
   */
  private String code;
  /**
   * 类别名称
   */
  private String name;
  /**
   * 排序等级
   */
  private Integer orderLevel;
  /**
   * 分类等级
   */
  private Integer cateLevel;
  /**
   * 状态（-1：停用 1：启用）
   */
  private Short status;
}
